package cn.chrilwe.pigpig.im.rabbit.factory.impl;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import cn.chrilwe.pigpig.im.rabbit.common.RabbitConfiguration;
import cn.chrilwe.pigpig.im.rabbit.factory.RabbitSession;
import cn.chrilwe.pigpig.im.rabbit.factory.RabbitSessionFactory;
/**
 * 
 * @author chrilwe
 * 2020-8-16
 */
public class DefaultRabbitSessionFactory implements RabbitSessionFactory {

	private RabbitConfiguration config;
	
	public DefaultRabbitSessionFactory(RabbitConfiguration config) {
		this.config = config;
	}
	
	@Override
	public RabbitSession openSession() {
		Connection connection = null;
		try {
			connection = getConnection();
			RabbitSessionTemplate template = new RabbitSessionTemplate(connection);
			return template;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TimeoutException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	private Connection getConnection() throws IOException, TimeoutException {
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost(config.getHost());
		factory.setConnectionTimeout(config.getConnectionTimeout());
		factory.setPort(config.getPort());
		factory.setUsername(config.getUsername());
		factory.setPassword(config.getPassword());
		return factory.newConnection();
	}
	
}
